﻿using System;

namespace Zive.Color {

    public static class ExtensionMethods {

        public static bool NearlyEqual( this float a, float b ) {
            float absA = Math.Abs( a );
            float absB = Math.Abs( b );
            float diff = Math.Abs( a - b );

            if ( a == b ) { // shortcut, handles infinities
                return true;
            } else if ( ( a == 0f ) || ( b == 0f ) || ( diff < float.MinValue ) ) {
                // a or b is zero or both are extremely close to it
                // relative error is less meaningful here
                return diff < ( float.Epsilon * float.MinValue );
            } else { // use relative error
                return diff / ( absA + absB ) < float.Epsilon;
            }
        }

        public static bool NearlyEqual( this double a, double b ) {
            double absA = Math.Abs( a );
            double absB = Math.Abs( b );
            double diff = Math.Abs( a - b );

            if ( a == b ) { // shortcut, handles infinities
                return true;
            } else if ( ( a == 0d ) || ( b == 0d ) || ( diff < double.MinValue ) ) {
                // a or b is zero or both are extremely close to it
                // relative error is less meaningful here
                return diff < ( double.Epsilon * double.MinValue );
            } else { // use relative error
                return diff / ( absA + absB ) < double.Epsilon;
            }
        }

    }

}
